using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;

namespace OA.UI
{
    public class UploadFile
    {
        public Common.Result Save(HttpPostedFileBase postedFile, Model.Config.UploadConfig config, bool? isImage, bool isThumbnai, bool? isWatermark)
        {
            Common.Result ret = new Common.Result(false,0, null);
            if (postedFile == null)
            {
                ret.message = "请选择要上传的文件";
                return ret;
            }

            if (isImage==null)
            {
                isImage = Common.Utils.IsImageFile(postedFile.FileName);
            }

            if(isImage.Value)
            {
                
                if (isWatermark != null && isWatermark.Value == false) config.WatermarkType = 0;
                ret = SaveImage(postedFile, config,isThumbnai);
            }
            else
            {
                ret=SaveFile(postedFile,config);
            }
            return ret;
        }

        public Common.Result SaveImage(HttpPostedFileBase postedFile, Model.Config.UploadConfig config, bool isThumbnai)
        {
            Common.Result ret = new Common.Result(false, 0, "");
            if (!Common.Utils.IsImageFile(postedFile.FileName))
            {
                ret.message = "上传的不是图片文件";
                return ret;
            }
            if (postedFile.ContentLength > config.AttachFileSize * 1024)
            {
                ret.message = "上传的图片大小超过最大限制(" + config.AttachImgSize.ToString() + "KB)";
                return ret;
            }
            ret = SaveTo(postedFile, config.AttachPath, config.AttachSave, config.AttachExtension);
            if (ret.success == false) return ret;

            var imgFilePath = ret.data.ToString();

            var img = System.Drawing.Image.FromStream(postedFile.InputStream);
            var width = img.Width;
            var height = img.Height;
            if ((config.AttachImgMaxHeight > 0 && config.AttachImgMaxHeight < img.Height) || (config.AttachImgMaxWidth > 0 && config.AttachImgMaxWidth < img.Width))
            {
                if (config.AttachImgMaxWidth > 0 && config.AttachImgMaxWidth < width) width = config.AttachImgMaxWidth;
                if (config.AttachImgMaxHeight > 0 && config.AttachImgMaxWidth < height) height = config.AttachImgMaxHeight;
                if (config.AttachImgIsScale)
                {
                    var bir = img.Width * 1.0 / img.Height;  //宽高比
                    if (width > height)
                    {
                        width = Convert.ToInt32(height * bir);
                    }
                    else
                    {
                        height = Convert.ToInt32(width / bir);
                    }
                }
                Common.Img.ImageClass.MakeThumbnail(Common.Utils.GetMapPath(imgFilePath), Common.Utils.GetMapPath(imgFilePath), width, height, "HW");
            }

            if (isThumbnai) //缩略图
            {
                var thwidth = config.ThumbnailWidth;
                var thheight = config.ThumbnailHeight;
                if (config.ThumbnailIsScale)
                {
                    var bir = width * 1.0 / height;
                    if (thwidth > thheight)
                    {
                        thwidth = Convert.ToInt32(thheight * bir);
                    }
                    else
                    {
                        thheight = Convert.ToInt32(thwidth / bir);
                    }
                }
                var splitIndex = imgFilePath.LastIndexOf("/");
                var thumbnailFilePath = imgFilePath.Substring(0, splitIndex) + "/small" + imgFilePath.Substring(splitIndex + 1);
                Common.Img.ImageClass.MakeThumbnail(Common.Utils.GetMapPath(imgFilePath), Common.Utils.GetMapPath(thumbnailFilePath), thwidth, thheight, "HW");
                
                ret.data += "," + thumbnailFilePath;
            }

            if (config.WatermarkType == 1)  //文字水印
            {
                Common.Img.ImageClass.AddImageSignText(imgFilePath, imgFilePath, config.WatermarkText,
                    config.WatermarkPosition, 100, config.WatermarkFont, config.WatermarkFontSize);
            }
            else if (config.WatermarkType == 2) //图片水印
            {
                if (System.IO.File.Exists(Common.Utils.GetMapPath(config.WatermarkPic)))
                {
                    Common.Img.ImageClass.AddImageSignPic(imgFilePath, imgFilePath, config.WatermarkPic,
                        config.WatermarkPosition, config.WatermarkImgQuality, config.WatermarkTransparency);
                }
                else  //图片不存在使用文字水印
                {
                    Common.Img.ImageClass.AddImageSignText(imgFilePath, imgFilePath, config.WatermarkText,
                    config.WatermarkPosition, 100, config.WatermarkFont, config.WatermarkFontSize);
                }
            }
            return ret;
        }

        public Common.Result SaveFile(HttpPostedFileBase postedFile, Model.Config.UploadConfig config)
        {
            Common.Result ret = new Common.Result(false, 0, "");
            if (postedFile.ContentLength > config.AttachFileSize * 1024)
            {
                ret.message = "上传的文件大小超过最大限制(" + config.AttachFileSize.ToString() + "KB)";
                return ret;
            }
            ret = SaveTo(postedFile, config.AttachPath, config.AttachSave,config.AttachExtension);
            return ret;

        }

        private Common.Result SaveTo(HttpPostedFileBase postedFile, string path, int saveType,string allowFileType)
        {
            Common.Result ret = new Common.Result(false, 0, "");
            string ext=Path.GetExtension(postedFile.FileName);
            var allowFiles = allowFileType.Split(',');
            if (allowFiles.All(r => "." + r != ext))
            {
                ret.message = "不允许上传此类型文件。允许上传的文件类型：" + allowFileType;
                return ret;
            }
            switch (saveType)
            {
                case 1: //年月日
                    path += "/" + DateTime.Now.ToString("yyyyMMdd");
                    break;
                case 2: //年月
                    path += "/" + DateTime.Now.ToString("yyyyMM");
                    break;
            }
            try
            {
                path = Utils.Url.Content(path);
                var tpath = Common.Utils.GetMapPath(path);
                if (!Directory.Exists(tpath)) Directory.CreateDirectory(tpath);
                path += "/" + Common.Utils.GetRamCode() + ext;
                postedFile.SaveAs(Common.Utils.GetMapPath(path));
                ret.success = true;
                ret.message = "上传成功";
                ret.data = path;
            }
            catch (Exception e)
            {
                ret.message = e.Message;
            }
            return ret;
        }
    }
}
